package crypto

import (
	"os"
	"strconv"
)

// CurveType represents the type of elliptic curve to use
type CurveType int

const (
	// BLS12_381 uses BLS12-381 pairing-friendly curve
	BLS12_381 CurveType = iota
	// Secp256k1 uses secp256k1 curve (faster verification)
	Secp256k1
)

// Global curve configuration
var (
	CurrentCurve CurveType = Secp256k1 // Default to Secp256k1 for better performance
	UseSecp256k1 bool      = true      // Flag to enable secp256k1
)

// InitCurveConfig initializes the curve configuration from environment variables
func InitCurveConfig() {
	// Check environment variable for curve type
	if curveEnv := os.Getenv("ADKR_CURVE"); curveEnv != "" {
		switch curveEnv {
		case "secp256k1", "SECP256K1":
			CurrentCurve = Secp256k1
			UseSecp256k1 = true
		case "bls12-381", "BLS12-381", "bls12381", "BLS12381":
			CurrentCurve = BLS12_381
			UseSecp256k1 = false
		default:
			// Keep default
		}
	}
	
	// Check for explicit flag
	if useSecpEnv := os.Getenv("ADKR_USE_SECP256K1"); useSecpEnv != "" {
		if useSecp, err := strconv.ParseBool(useSecpEnv); err == nil {
			UseSecp256k1 = useSecp
			if useSecp {
				CurrentCurve = Secp256k1
			} else {
				CurrentCurve = BLS12_381
			}
		}
	}
}

// SetCurveType sets the current curve type
func SetCurveType(curve CurveType) {
	CurrentCurve = curve
	UseSecp256k1 = (curve == Secp256k1)
}

// GetCurveType returns the current curve type
func GetCurveType() CurveType {
	return CurrentCurve
}

// IsSecp256k1 returns true if using secp256k1 curve
func IsSecp256k1() bool {
	return UseSecp256k1
}

// IsBLS12381 returns true if using BLS12-381 curve
func IsBLS12381() bool {
	return !UseSecp256k1
}

// GetCurveName returns the name of the current curve
func GetCurveName() string {
	switch CurrentCurve {
	case Secp256k1:
		return "secp256k1"
	case BLS12_381:
		return "bls12-381"
	default:
		return "unknown"
	}
}

// CurveConfig represents curve configuration
type CurveConfig struct {
	Type CurveType
	Name string
}

// GetCurveConfig returns the current curve configuration
func GetCurveConfig() CurveConfig {
	return CurveConfig{
		Type: CurrentCurve,
		Name: GetCurveName(),
	}
}

// Initialize curve configuration on package load
func init() {
	InitCurveConfig()
}
